<template>
  <div class="app-container">
    <el-row :gutter="20" style="height: 40px"></el-row>
    <el-row :gutter="20">
      <el-col :span="16">
        <div class="grid-content ">
          <div class="taobao-like">淘宝宝</div>
          <div class="taobao-e">taobaobao</div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="grid-content  ">
          <el-input
              v-model="input"
              style="width: 240px;height: 55px;"
              placeholder="Please input"
              clearable
              class="rounded-input"
          />
          <el-button type="primary" style="height: 55px" @click="search" class="rounded-search">搜本店</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="20" class="content-row">
      <el-col :span="14">
        <div class="grid-contents">
          <el-scrollbar height="1200px" @end-reached="loadMore">
            <div class="ke-fu">
              <el-col :span="3">
                <div style="width: 100%">客服</div>
              </el-col>
              <el-col :span="14">
                <div style="width: 100%;">
                  <p style="font-size: 20px">{{shop.shopName}}</p>
                  <p style="color: #FFA500">
                    <el-icon v-for="n in 5" :key="n" :style="{ color: n <= starCount ? '#FFA500' : '#CCCCCC' }">
                      <StarFilled/>
                    </el-icon>
                    {{ rating }}
                  </p>
                </div>
              </el-col>
              <el-col :span="3">
                <div class="button-container">
                  <el-button type="primary" class="custom-button">
                    <el-icon>
                      <ChatDotRound/>
                    </el-icon>
                    客服
                  </el-button>
                </div>
              </el-col>
              <el-col :span="3">
                <div class="button-container">
                  <el-button type="primary" @click="jindian" class="custom-button">
                    <el-icon>
                      <Shop/>
                    </el-icon>
                    进店
                  </el-button>
                </div>
              </el-col>
            </div>
            <div class="image-gallery">
              <div class="image-container">
                <div class="thumbnail-container">
                  <el-scrollbar height="450px" @end-reached="loadMore">
                    <div class="thumbnail-list">
                      <el-image
                          v-for="(item, index) in imageList"
                          :key="index"
                          :src="item.url"
                          class="thumbnail"
                          @click="activeIndex = index"
                          :class="{ active: activeIndex === index }"
                          fit="cover"
                          lazy
                      />
                    </div>
                  </el-scrollbar>
                </div>
                <div class="large-image-container">
                  <el-image
                      v-if="imageList.length > 0"
                      :src="imageList[activeIndex].url"
                      fit="contain"
                      lazy
                      style="width: 100%; height: 100%;"
                  />
                  <div v-else class="empty-state">暂无图片数据</div>
                </div>
              </div>
            </div>
            <div style="font-size: 20px; font-weight: bold;">用户评价</div>
            <p v-for="item in num" :key="item" class="scrollbar-demo-item">
              {{ item }}
            </p>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="10">
        <div class="grid-contentss">
        </div>
        <div>
          <el-scrollbar height="450px" @end-reached="loadMore">
            <div><h2>{{ product.name }}</h2>
              <div class="price-container">
                <div class="price-info">
                  <span class="price-after" style="font-size: 15px">券后</span>
                  <span class="price-after" style="font-size: 30px">¥{{ product.priceAfter }}</span>
                  <span class="price-before" style="font-size: 15px">优惠前¥{{ product.priceAfter }}</span>
                  <span class="sales" style="font-size: 15px">已售1万+</span>
                </div>
              </div>
            </div>
            <div
                class="product-options"
                v-for="(specValues, specName) in allSpecs"
                :key="specName"
            >
              <h3 class="option-title">{{ specName }}</h3>
              <el-radio-group
                  v-model="selectedSpecs[specName]"
                  class="color-options"
              >
                <el-radio
                    v-for="(item, index) in specValues"
                    :key="index"
                    :label="item.label"
                    class="color-option"
                >
                  <el-image
                      v-if="item.img"
                      :src="item.img"
                      alt="规格预览"
                      fit="cover"
                      class="color-img"
                  >
                    <template #error>
                      <div class="color-img-placeholder">{{ item.label.charAt(0) }}</div>
                    </template>
                  </el-image>
                  <span class="color-name">{{ item.label }}</span>
                </el-radio>
              </el-radio-group>
            </div>
          </el-scrollbar>
        </div>
        <div class="product-actions">
          <el-button
              type="primary"
              size="large"
              @click="addToCart"
              class="action-btn add-to-cart-btn"
          >
            加入购物车
          </el-button>
          <el-button
              type="success"
              size="large"
              @click="buyWithCoupon"
              class="action-btn buy-with-coupon-btn"
          >
            领券购买
          </el-button>
          <el-button
              size="large"
              @click="collect"
              :icon="isCollected ? 'el-icon-star-on' : 'el-icon-star-off'"
              class="action-btn collect-btn"
          >
            {{ isCollected ? '已收藏' : '收藏' }}
          </el-button>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import {onMounted, ref} from 'vue'
import type {ScrollbarDirection} from 'element-plus'
import {ElImage, ElMessage} from 'element-plus'
import {ChatDotRound, Shop, StarFilled} from '@element-plus/icons-vue'
import axios from 'axios';
import {useRouter} from 'vue-router';
const router = useRouter();

const shop = ref({
  logo: '',
  shopName: '',
})
const product = ref({
  shopId: '',
  id: 1,
  name: '',
  priceBefore: '',
  priceAfter: '',
  img: '',
  buyed: 0,
  mainImg: '',
});

const fetchImageList = async () => {
  const mockResponse = [
    {url: 'https://picsum.photos/400/500?random=1'},
    {url: 'https://picsum.photos/400/500?random=2'},
    {url: 'https://picsum.photos/400/500?random=3'},
    {url: 'https://picsum.photos/400/500?random=4'},
    {url: 'https://picsum.photos/400/500?random=1'},
    {url: 'https://picsum.photos/400/500?random=2'},
    {url: 'https://picsum.photos/400/500?random=3'},
    {url: 'https://picsum.photos/400/500?random=4'},
  ]
  return mockResponse
}

const imageList = ref([])
const activeIndex = ref(0)

const loading = ref(true);
const error = ref(false);
const isCollected = ref(false);
const selectedInfo = ref('');
const allSpecs = ref<Record<string, any[]>>({});
const selectedSpecs = ref<Record<string, string>>({});
const  doShop = async () => {
  const shopRes = await axios.get('/api/shop', {
    params: {
      id: product.value.shopId
    }

  });
  shop.value = shopRes.data;
}
const jindian=()=>{
  router.push(
      {
        name: 'Shop',
        params: {
          id: product.value.shopId
        }
      }
  )
}
const doProduct = async () => {
  loading.value = true;
  error.value = false;
  try {
    const productRes = await axios.get(`/api/product/select/${product.value.id}`);
    console.log('商品基本信息:', productRes.data);
    product.value = productRes.data;
    if (product.value.img) {
      const imgUrls = product.value.img.split(',').map(url => url.trim());
      imageList.value = imgUrls.map(url => ({url}));
    }

    const specsRes = await axios.post('/api/product/Productspec', {
      productId: product.value.id
    });
    console.log('规格信息原始数据:', specsRes.data);
    const specsData = specsRes.data;

    allSpecs.value = {};
    selectedSpecs.value = {};

    for (const spec of specsData) {
      try {
        console.log(`正在处理规格: ${spec.specName} (ID: ${spec.id})`);

        const specValuesRes = await axios.post('/api/product/ProductspecValue/select', {
          specId: spec.id
        });
        console.log(`规格 ${spec.specName} 的值:`, specValuesRes.data);

        if (!specValuesRes.data || specValuesRes.data.length === 0) {
          console.warn(`规格 ${spec.specName} 没有返回任何值`);
          continue;
        }

        allSpecs.value[spec.specName] = specValuesRes.data.map((specValue: any) => ({
          label: specValue.value || specValue.specName || '默认',
          img: specValue.img || specValue.image || '',
          id: specValue.id
        }));

        if (specValuesRes.data.length > 0) {
          selectedSpecs.value[spec.specName] = specValuesRes.data[0].value || specValuesRes.data[0].name || '默认';
        }
      } catch (specError) {
        console.error(`获取规格 ${spec.name} 的值失败:`, specError);
      }
    }
    console.log('allSpecs键名:', Object.keys(allSpecs.value));
    console.log('最终的allSpecs:', allSpecs.value);
    console.log('最终的selectedSpecs:', selectedSpecs.value);

    if (allSpecs.value['颜色']) {
      console.log('颜色规格存在，值为:', allSpecs.value['颜色']);
    } else {
      console.log('未找到颜色规格');
      const colorKeys = Object.keys(allSpecs.value).filter(key =>
          key.includes('颜色') || key.toLowerCase().includes('color')
      );
      if (colorKeys.length > 0) {
        console.log('可能的颜色规格键名:', colorKeys);
      }
    }
  } catch (err) {
    console.error('获取商品数据失败:', err);
    error.value = true;
    ElMessage.error('获取商品信息失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

const addToCart = () => {
  selectedInfo.value = Object.entries(selectedSpecs.value as Record<string, string>)
      .map(([specName, specValue]) => `${specName}: ${specValue}`)
      .join(', ');
  ElMessage.success(`【${product.value.name}】已加入购物车，规格: ${selectedInfo.value}`);
  router.push({
    path: '/sss',
    query: {
      id: selectedInfo.value,
    }
  })
};

const buyWithCoupon = () => {
  selectedInfo.value = Object.entries(selectedSpecs.value as Record<string, string>)
      .map(([specName, specValue]) => `${specName}: ${specValue}`)
      .join(', ');
  ElMessage.success(`即将领券购买【${product.value.name}】，规格: ${selectedInfo.value}`);
};

const collect = () => {
  isCollected.value = !isCollected.value;
  ElMessage.success(isCollected.value ? '收藏成功' : '取消收藏');
};

onMounted(async () => {
  doProduct();
  doShop();
  imageList.value = await fetchImageList()
})

const rating = ref(3.6)

const getStarCount = (rating: number) => {
  return Math.ceil(rating);
}

const starCount = ref(getStarCount(rating.value));
const input = ref('')
const num = ref(30)

const search = () => {
  console.log('Searching for:', input.value)
}

const loadMore = (direction: ScrollbarDirection) => {
  if (direction === 'bottom') {
    num.value += 5
  }
}
</script>

<style scoped>
.app-container {
  display: flex;
  flex-direction: column;
  padding-left: 100px;
  padding-right: 100px;
  padding-top: 30px;
}

.ke-fu {
  height: 80px;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 10px;
  padding: 0 20px;
}

.taobao-like {
  font-family: 'SimilarToTaobao', "Microsoft YaHei", "微软雅黑", sans-serif;
  font-size: 24px;
  font-weight: 600;
  color: #FF4400;
  letter-spacing: -0.5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.taobao-e {
  font-family: 'SimilarToTaobao', "Microsoft YaHei", "微软雅黑", sans-serif;
  font-size: 14px;
  font-weight: 600;
  color: #FF4400;
  letter-spacing: -0.5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.grid-content {
  font-family: "Microsoft YaHei", Arial, sans-serif;
  height: 55px;
  border-radius: 4px;
  min-height: 36px;
}

.grid-contents {
  height: 100%;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  border-radius: 4px;
  min-height: 36px;
}

.grid-contentss {
  margin-top: 50px;
  background: red;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  border-radius: 4px;
  min-height: 36px;
}

.rounded-input :deep(.el-input__wrapper) {
  border-radius: 15px 0px 0px 15px;
}

.rounded-search {
  border-radius: 0 15px 15px 0;
  background: #FF4400;
}

.content-row {
  flex: 1;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  margin: 10px;
  text-align: center;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.el-slider {
  margin-top: 20px;
}

.button-container .custom-button {
  width: 100%;
  height: 50px;
  background: white;
  color: #409eff;
  border-color: #409eff;
}

.button-container .el-button {
  width: 100%;
  height: 50px;
  background: white;
}

.image-gallery {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.image-container {
  display: flex;
  gap: 20px;
  height: 450px;
}

.thumbnail-container {
  width: 100px;
  flex-shrink: 0;
}

.thumbnail-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.thumbnail {
  width: 100px;
  height: 100px;
  cursor: pointer;
  border: 2px solid transparent;
  border-radius: 4px;
  transition: border-color 0.3s;
  flex-shrink: 0;
}

.thumbnail.active {
  border-color: #409eff;
}

.thumbnail:hover {
  border-color: #66b1ff;
}

.large-image-container {
  flex: 1;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #eee;
  border-radius: 8px;
  background-color: #fafafa;
}

.empty-state {
  color: #999;
  font-size: 16px;
}

.price-info {
  display: inline-flex;
  align-items: center;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
  color: #333;
  line-height: 1;
}

.price-before {
  text-decoration: line-through;
  color: #999;
  font-size: 14px;
  margin-right: 6px;
}

.price-after {
  color: #ff4d4f;
  font-size: 16px;
  font-weight: 700;
  margin-right: 8px;
}

.sales {
  font-size: 12px;
  color: #666;
}

.product-options {
  margin-bottom: 30px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 6px;
}

.option-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #333;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

.color-options {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.color-option {
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #fff;
}

.color-option:hover {
  border-color: #409eff;
  box-shadow: 0 2px 5px rgba(64, 158, 255, 0.1);
  transform: translateY(-2px);
}

.el-radio__input.is-checked + .color-option {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.color-img {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  vertical-align: middle;
  border-radius: 4px;
}

.color-img-placeholder {
  width: 50px;
  height: 50px;
  background-color: #eee;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  border-radius: 4px;
}

.color-name {
  vertical-align: middle;
}

.product-actions {
  display: flex;
  gap: 15px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  flex-shrink: 0;
}

.action-btn {
  flex: 1;
  min-width: 120px;
  height: 50px;
  font-size: 16px;
  font-weight: 500;
}

.add-to-cart-btn {
  background-color: #FFA500;
  border-color: #FFA500;
}

.buy-with-coupon-btn {
  background-color: #FF4500;
  border-color: #FF4500;
}

.collect-btn {
  flex: 0 0 50px;
  background-color: transparent;
  color: #FFA500;
  border-color: transparent;
}

.collect-btn:hover {
  color: #FF4500;
}
</style>
